package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);//默认端口可以不设置
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();
        // 定义队列
        c.queueDeclare("task_queue1", true, false, false, null);


        // 创建回调对象
        //处理消息的回调函数
        DeliverCallback deliverCallback=new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                byte[] s = message.getBody();
                String msg = new String(s);
                System.out.println("收到："+msg);
                //遍历字符串，每个点字符暂停一秒
                for (int i = 0; i < msg.length(); i++) {
                    if('.'==msg.charAt(i)){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //手动发送回执
                //第二个参数：是否把之前接收的所有消息一起都进行确认
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
                System.out.println("-------消息处理结束-------");
            }
        };
        //取消处理消息的回调函数
        CancelCallback cancelCallback=new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        //每次只抓取一条消息，处理完成之前不会抓取下一条，只在手动确认下有效
        c.basicQos(1);

        //接收消息
        //第二个参数：true自动确认（Ack），false手动确认
        c.basicConsume("task_queue1", false,deliverCallback,cancelCallback);
    }
}
